package com.tzy.rpc.loadbalancer;/**
 * @description:
 * @Author HP
 * @create 2022/3/18 20:42
 */

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import redis.clients.jedis.Jedis;

import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

/**
 * @author HP
 * @create 2022-03-18 20:42
 * @desc 轮询算法
 **/
public class RoundRobinLoadBalancer implements LoadBalancer{
    private static Integer index = 0;
    private Jedis jedis=new Jedis("localhost", 6379);

    @Override
    public Instance select(List<Instance> instances) {
        int size=instances.size();
        String serviceName = instances.get(0).getServiceName().substring(15);
        int index =-1;
        String script=null ;
        try (
                InputStreamReader reader = new InputStreamReader(RoundRobinLoadBalancer.class.getResourceAsStream("/luaScript/lockAndRelease.lua"));
                ){
            script = CharStreams.toString(reader);
            index=((Long)jedis.eval(script, Lists.newArrayList(serviceName+":idx",serviceName+":cnt",serviceName+":lock"), Lists.newArrayList(size+"", UUID.randomUUID()+""))).intValue();
            while (index==-1){
                index = ((Long)jedis.eval(script, Lists.newArrayList(serviceName+":idx",serviceName+":cnt",serviceName+":lock"), Lists.newArrayList(size+"", UUID.randomUUID()+""))).intValue();
            }
        }catch (Exception e){
            e.printStackTrace();
            index = ((Long)jedis.eval(script, Lists.newArrayList(serviceName+":idx",serviceName+":cnt",serviceName+":lock"), Lists.newArrayList(size+"", UUID.randomUUID()+""))).intValue();
        }
        System.out.println("使用服务："+serviceName+index);
        return instances.get(index);
    }
}
